<?php
/**
 * POS
 * @property Item $Item
 * @property Sale $Sale
 * @property SaleItem $SaleItem
 * @property Refund $Refund
 * @property Payment $Payment
 * @property PaymentType $PaymentType
 * @property Layby $Layby
 * @property LaybyPayment $LaybyPayment
 * */
App::uses ( 'AppController', 'Controller' );
class PagesController extends AppController {
	var $item_session_name = "myitems_session_name";
	public $uses = array (
			"Item",
			"Customer",
			"PointOfSale.Sale",
			"PointOfSale.SaleItem",
			"PointOfSale.Refund",
			"PointOfSale.Payment",
			"PointOfSale.PaymentType",
			"PointOfSale.Layby",
			"PointOfSale.LaybyPayment" 
	);
	public $paginate = array (
			'Sale' => array (
					'order' => array (
							'Sale.id' => 'desc' 
					) 
			),
			'Layby' => array (
					'order' => array (
							'Layby.id' => 'desc' 
					) 
			) 
	);
	/**
	 * sale table
	 */
	public function display() {
		// read item in session
		$this->salesadd ();
	}
	/**
	 * Add item (session)
	 */
	public function salesadd() {
		if ($this->request->is ( "ajax" )) {
			$this->layout = null;
			$this->view = "Elements/salesadd";
		}
		$item_id = $this->request->data ( "item" );
		$sale = $this->Session->read ( $this->item_session_name );
		// echo json_encode ( $sale );
		if (empty ( $sale )) {
			$sale = array (
					"cart_count" => 0,
					"sub_total" => 0,
					"discount" => 0,
					"discount_type" => 0,
					"payment_type" => 0,
					"payment" => 0,
					"total" => 0,
					"balance" => 0,
					"laybyed" => false,
					"customer" => array (),
					"items" => array () 
			);
		}
		// if not added yet, add
		if (! key_exists ( $item_id, $sale ["items"] ) && $item_id > 0) {
			$item = $this->Item->find ( "first", array (
					"conditions" => array (
							"Item.id" => $item_id 
					),
					"fields" => array (
							"Item.id",
							"Item.name",
							"Item.original_price",
							"Brand.name",
							"Color.name" 
					) 
			) );
			$item ["Item"] ["discount"] = 0;
			$item ["Item"] ["discount_type"] = 0;
			$item ["Item"] ["layby_amount"] = 0;
			$item ["Item"] ["total"] = $item ["Item"] ["original_price"];

			$sale ["items"] [$item_id] = $item;
		}
		
		// calculate total
		if (! empty ( $sale ["items"] )) {
			$cart_count = 0;
			$sub_total = 0;
			$total = 0;
			$sale ["laybyed"] = false;
			foreach ( $sale ["items"] as $k => $v ) {
				$cart_count ++;
				$sub_total += $v ["Item"] ["original_price"];
				$item_total = $v ["Item"] ["total"];
				// if include discounting, then calculate the total again
				if (! empty ( $v ["Item"] ["discount"] )) {
					if (empty ( $v ["Item"] ["discount_type"] )) {
						//discount by percentage
						$item_total = $sale ["items"] [$k] ["Item"] ["total"] = $v ["Item"] ["original_price"] * (100 - intval ( $v ["Item"] ["discount"] )) / 100;
					} else {
						// discount by amount
						$item_total = $sale ["items"] [$k] ["Item"] ["total"] = $v ["Item"] ["original_price"] - doubleval ( $v ["Item"] ["discount"] );
					}
				}
				// if involves layby payment
				if (! empty ( $v ["Item"] ["layby_amount"] )) {
					$item_total = $v ["Item"] ["layby_amount"];
					$sale ["laybyed"] = true;
				}
				$total += $item_total;
			}
			$sale ["cart_count"] = $cart_count;
			$sale ["sub_total"] = $sub_total;
			// if therer is discount by total
			if (! empty ( $sale ["discount"] )) {
				if (empty ( $sale ["discount_type"] )) {
					// discount by percentage
					$total = $total * (100 - intval ( $sale ["discount"] )) / 100;
				} else {
					// discount by amount
					$total = $total - doubleval ( $sale ["discount"] );
				}
			}
			// check payment remaining balance
			if (! empty ( $sale ["id"] )) {
				$this->Sale->id = $sale ["id"];
				$sale ["balance"] = $this->Sale->field ( "balance" );
			} else {
				$sale ["balance"] = $total;
			}
			$sale ["total"] = $total;
		} else {
			// if not item in sale list,, sale is empty
			$sale = array (
					"cart_count" => 0,
					"sub_total" => 0,
					"discount" => 0,
					"discount_type" => 0,
					"payment_type" => 0,
					"payment" => 0,
					"total" => 0,
					"balance" => 0,
					"customer" => array (),
					"items" => array () 
			);
		}
		//check payment type
		$payment_types = $this->PaymentType->find ( "all" );
		$this->set ( "payment_types", $payment_types );
		$this->set ( "sale", $sale );
		$this->Session->write ( $this->item_session_name, $sale );
	}
	/**
	 * update shopping cart
	 */
	public function edit_item() {
		$typeid = $this->request->params ["id"];
		$sale = $this->Session->read ( $this->item_session_name );
		$redirect_url="/Point_of_sale";
		switch ($typeid) {
			case 1 :
				// 1.update item individual discount
				$id = $this->request->data ( "id" );
				$price = $this->request->data ( "price" );
				$discount_type = $this->request->data ( "discount_type" );
				$discount = $this->request->data ( "discount" );
				$layby_amount = $this->request->data ( "layby_amount" );
				if (! empty ( $sale ["items"] [$id] )) {
					$sale ["items"] [$id] ["Item"] ["original_price"] = $price;
					$sale ["items"] [$id] ["Item"] ["discount_type"] = $discount_type;
					$sale ["items"] [$id] ["Item"] ["discount"] = $discount;
					$sale ["items"] [$id] ["Item"] ["layby_amount"] = $layby_amount;
				} else {
					$this->Session->setFlash ( "Item " . $id . " not exists!!" );
				}
				break;
			case 2 :
				// 2.update the total sale discount
				$discount_type = $this->request->data ( "discount_type" );
				$discount = $this->request->data ( "discount" );
				$sale ["discount"] = $discount;
				$sale ["discount_type"] = $discount_type;
				break;
			case 3 :
				// 3.update customer's id and name
				$cus_id = $this->request->data ( "customer" ); //cust id
				if ($cus_id > 0) {
					$customer = $this->Customer->find ( "first", array (
							"conditions" => array (
									"Customer.id" => $cus_id 
							),
							"fields" => array (
									"Customer.id",
									"Customer.email",
									"Customer.first_name",
									"Customer.last_name" 
							) 
					) );
					$sale ["customer"] = array (
							"id" => $cus_id,
							"name" => $customer ["Customer"] ["first_name"] . " " . $customer ["Customer"] ["last_name"],
							"email" => $customer ["Customer"] ["email"] 
					);
				} else {
					// clear customer info
					unset ( $sale ["customer"] );
				}
				break;
			case 4 :
				// 4.update payment type(payment)amount_tendered/payment payment_type

				$amount_tendered = $this->request->data ( "amount_tendered" );
				$payment_type = $this->request->data ( "payment_type" );
				$sale_id = $this->request->data ( "id" );
				$sale ["payment"] = doubleval ( $amount_tendered );
				$sale ["payment_type"] = intval ( $payment_type );
				$sale ["customer_id"] = $this->request->data ( "cId" );
				$sale ["id"] = $sale_id;
				// if continue paying, check previous remaining balance
				if ($sale_id > 0) {
					$this->Sale->id = $sale_id;
					$sale ["balance"] = $this->Sale->field ( "balance" );
				}
				$message = "Payment successful!!";
				if ($sale_id > 0 && $sale ["balance"] < 1) {
					$message = "Refund successful!!";
				}
				$sale ["balance"] = $sale ["balance"] - $sale ["payment"];
				if ($sale ["balance"] < 1) {
					$sale ["balance"] = 0;
				}
				// can process sale even without customer
				// if (empty ( $sale ["customer"] ["id"] )) {
				// $this->Session->setFlash ( 'Customers must choose!!' );
				// break;
				// }
				// save sale detail result
				$sale_id=$sale ["id"] = $this->saveSale ( $sale );
				// payment done,, can make another payment
				// if haven't paid all amount, then continue with second payment
				$this->Session->setFlash ( $message );
				if ($sale ["balance"] < 1) {
					$sale = array ();
					///Sales/receipt/23
				$redirect_url_special=$this->request->data ( "SiteURL" )."/Sales/receipt/".$sale_id;
                }
				break;
			case 5 :
				// remove cart
				// get the cart id that needs to be removed
				$id = $this->request->data ( "id" );
				if (! empty ( $id )) {
					$item_id = explode ( ";", $id );
					foreach ( $item_id as $i ) {
						if (! empty ( $i )) {
							unset ( $sale ["items"] [$i] );
						}
					}
				}
				break;
			case 6 :
				// refund, need saleid and itemid
				$sale_id = $this->request->data ( "sale_id" );
				$sale_id = intval ( $sale_id );
				//may have many id
				$item_id = $this->request->data ( "item_id" );
				if (empty ( $item_id ) || empty ( $sale_id )) {
					$this->Session->setFlash ( 'Item or a sale can not be empty!!' );
					break;
				}
				$item_ids = explode ( ";", $item_id );
				$item_ids_2 = array ();
				foreach ( $item_ids as $iid ) {
					if (! empty ( $iid )) {
						$item_ids_2 [] = $iid;
					}
				}
				if (empty ( $item_ids_2 )) {
					$this->Session->setFlash ( 'Item or a sale can not be empty!!' );
					break;
				}
				$item_id_arr_str = implode ( ",", $item_ids_2 );
				// @todo 1.标记sale_item的状态，2.重新统计sale的总金额和余额(直接sql语句更新)
				$sql = "UPDATE item_sale SET STATUS=1 WHERE sale_id=$sale_id AND item_id in($item_id_arr_str)";
				// 更新sale_item的状态
				$result = $this->SaleItem->query ( $sql );
				$update_balance = "UPDATE sale AS d,(SELECT b.sum_o_price,b.sum_b_price,b.sale_id,
	IF(sa.discount_type='Amount', b.sum_b_price-sa.discount_amout , b.sum_b_price*(1-sa.discount_amout/100)) AS total_price,
	IF(sa.discount_type='Amount', b.sum_b_price-sa.discount_amout , b.sum_b_price*(1-sa.discount_amout/100))
	-(SELECT SUM(amount) AS pay_price FROM payment WHERE sale_id=sa.id) AS sale_balance
	FROM (
	SELECT SUM(a.original_price) AS sum_o_price,SUM(a.balance) AS sum_b_price,a.sale_id
		FROM (
			SELECT original_price,discount_amount,sale_id,
			IF(discount_type='Amount', original_price-discount_amount , original_price*(1-discount_amount/100)) AS balance
			FROM items AS it LEFT JOIN item_sale AS its ON it.id=its.item_id WHERE sale_id=$sale_id AND its.status=0
		) AS a ) AS b
	LEFT JOIN sale AS sa ON b.sale_id=sa.id ) AS c SET d.balance=c.sale_balance,d.sale_original_price=c.sum_o_price,d.sale_price=c.total_price 
	WHERE d.id=$sale_id";
				// 更新sale的总价，折扣后的价格，余额
				$this->SaleItem->query ( $update_balance );
				// 查询余额是否为负数，（负数是因为支付的金额，大于了商品的金额）
				$this->Sale->id = $sale_id;
				$balance = $this->Sale->field ( "balance" );
				if ($balance >= 0) {
					$this->Session->setFlash ( 'Refund successful!!' );
				} else {
					$this->Session->setFlash ( 'Refund successful!! Need refund $' . abs ( $balance ) );
				}
				if (! empty ( $item_id_arr_str )) {
					// 更改item的销售状态为已已退货
					$sql = "UPDATE " . $this->Item->useTable . " set item_status_id=3 where id in(" . $item_id_arr_str . ")";
					$this->Item->query ( $sql );
				}
				// 设置成功之后，跳转到sales
				$this->redirect ( "/Sales" );
				break;
			case 7 :
				// 取消sale
				$sale = array ();
				// $this->Session->setFlash ( $message );
				break;
			default :
				break;
		}
		$this->Session->write ( $this->item_session_name, $sale );
		
		if(isset($redirect_url_special))
		{
			echo $redirect_url_special;exit;
		}
		else
		{
			$this->redirect ($redirect_url );
		}
	}
	/**
	 * Record sales
	 */
	private function saveSale($data = array()) {
		$customer_id = ! empty ( $data ["customer"] ["id"] ) ? intval ( $data ["customer"] ["id"] ) : 0;
		$sale = array (
				"customer_id" => $customer_id,
				"sale_price" => $data ["total"],
				"locaion_id" => 0,
				"balance" => $data ["balance"],
				"sale_original_price" => $data ["sub_total"],
				"sale_type" => 0,
				"discount_amout" => $data ["discount"],
				"discount_type" => empty ( $data ["discount_type"] ) ? "Percentage" : "Amount" 
		);
		if (! empty ( $data ["id"] )) {
			$sale_id = $data ["id"];
			// 只增加一条payment
			$payment = array (
					"sale_id" => $sale_id,
					"amount" => $data ["payment"],
					"payment_type_id" => $data ["payment_type"] 
			);
			if ($this->Payment->save ( $payment )) {
				// 更新sale的余额
				$this->Sale->id = $sale_id;
				$this->Sale->saveField ( "balance", $data ["balance"] );
				return $sale_id;
			}
		} else {
			// 保存sale
			if ($this->Sale->save ( $sale )) {
				$sale_id = $this->Sale->id;
				// 保存payment
				$payment = array (
						"sale_id" => $sale_id,
						"amount" => $data ["payment"],
						"payment_type_id" => $data ["payment_type"] 
				);
				$this->Payment->save ( $payment );
				// 保存sale_item
				$sale_item = array ();
				$item_ids = array ();
				$sale_layby_amount = 0;
				$layby_intitial_amount = 0;
				$item_count = 0;
				foreach ( $data ["items"] as $item ) {
					$item_ids [] = $item ["Item"] ["id"];
					$layby_amount = doubleval ( $item ["Item"] ["layby_amount"] );
					$sale_item [] = array (
							"sale_id" => $sale_id,
							"item_id" => $item ["Item"] ["id"],
							"status" => 0,
							"layby_amount" => $layby_amount,
							"discount_amount" => $item ["Item"] ["discount"],
							"discount_type" => empty ( $item ["Item"] ["discount_type"] ) ? "Percentage" : "Amount" 
					);
					if (! empty ( $layby_amount )) {
						$sale_layby_amount += $item ["Item"] ["original_price"];
						$layby_intitial_amount += $layby_amount;
						$item_count ++;
					}
				}
				// 新增分期记录
				if (! empty ( $layby_intitial_amount )) {
					$layby_id = $this->addIntitialLayby ( $sale_id, $item_count, $customer_id, $sale_layby_amount, $layby_intitial_amount );
					// 设置销售记录的分期编号
					foreach ( $sale_item as $k => $v ) {
						if (! empty ( $v ["layby_amount"] )) {
							$sale_item [$k] ["layby_id"] = $layby_id;
						}
					}
				}
				$this->SaleItem->saveMany ( $sale_item );
				if (! empty ( $item_ids )) {
					// 更改item的销售状态为已卖出
					$sql = "UPDATE " . $this->Item->useTable . " set item_status_id=2 where id in(" . implode ( ",", $item_ids ) . ")";
					$this->Item->query ( $sql );
				}
				
				return $sale_id;
			}
		}
		return 0;
	}
	/**
	 * 保存首期分期付款
	 */
	private function addIntitialLayby($sale_id, $item_count, $customer_id, $sale_amount, $intitial_amount) {
		$layby = array (
				"sale_id" => $sale_id,
				"amount" => $sale_amount,
				"item_count" => $item_count,
				"customer_id" => $customer_id,
				"amountdue" => $sale_amount - $intitial_amount,
				"intitial_amount" => $intitial_amount 
		);
		$this->Layby->save ( $layby );
		return $this->Layby->id;
	}
	// 销售记录
	public function sales() {
		if ($this->request->is ( "ajax" )) {
			$this->layout = null;
		}
		$this->set ( 'sales', $this->paginate ( "Sale" ) );
	}
	
	public function salesdata() {

        $this->autoRender = false;  
		$output = $this->Sale->GetData();	
		echo json_encode($output);
		exit;
		
	}
	public function viewsale() {
		$id = $this->request->params ["id"];
        $ajax=!empty($_REQUEST["ajax"]);
		if ($this->request->is ( "ajax" ) || $ajax) {
			$this->layout = null;
		}
		$this->set ( "id", $id );
		// 查询没有分期的item
		$saleItem = array ();
		$options = array (
				"conditions" => array (
						"SaleItem.layby_id" => "0",
						"SaleItem.sale_id" => $id 
				) 
		);
		$saleItem = $this->SaleItem->find ( "all", $options );
		//查询此次销售中，分期的物品
		$options = array (
				"conditions" => array (
						"SaleItem.layby_id >0",
						"SaleItem.sale_id" => $id 
				) 
		);
		$laybyItem = $this->SaleItem->find ( "all", $options );
		$this->set ( "laybyItem", $laybyItem );
		$this->set ( "saleItem", $saleItem );
        $this->set("ajax", $ajax);
	}
	/**
	 * 分期记录
	 */
	public function layby() {
		if ($this->request->is ( "ajax" )) {
			$this->layout = null;
		}
		$this->set ( 'laybys', $this->paginate ( "Layby" ) );
		
		// 查询支付类型
		$payment_types = $this->PaymentType->find ( "all" );
		$this->set ( "payment_types", $payment_types );
	}
	
	public function laybydata() {	

        $this->autoRender = false;  
		$output = $this->Layby->GetData();	
		echo json_encode($output);
		
	}
	
	/**
	 * 支付分期付款
	 */
	public function paylayby() {
		if ($this->request->is ( "post" )) {
			$id = $this->request->data ( "id" );
			$payment_type = $this->request->data ( "payment_type" );
			$amount = $this->request->data ( "amount" );
			$data = array (
					"layby_id" => $id,
					"amount" => $amount,
					"payment_type_id" => $payment_type 
			);
			if ($this->LaybyPayment->save ( $data )) {
				// 更新分期的支付余额
				$this->Layby->id = $id;
				$amountdue = $this->Layby->field ( "amountdue" );
				$amountdue = $amountdue - $amount;
				$this->Layby->saveField ( "amountdue", $amountdue );
				echo $this->LaybyPayment->id;
			}
		}
		die ();
	}
	/**
	 * 查看分期详细
	 */
	public function viewlayby() {
		$id = $this->request->params ["id"];
		if ($this->request->is ( "ajax" )) {
			$this->layout = null;
		}
		$this->set ( "id", $id );
		$laybyItem = array ();
		// 查询分期付款的item.
		$options = array (
				"conditions" => array (
						"SaleItem.layby_id" => $id 
				) 
		);
		$laybyItem = $this->SaleItem->find ( "all", $options );
		$this->set ( "laybyItem", $laybyItem );
		// 查询分期付款的支付
		$laybyPayments = array ();
		$options = array (
				"conditions" => array (
						"LaybyPayment.layby_id" => $id 
				) 
		);
		$laybyPayments = $this->LaybyPayment->find ( "all", $options );
		$this->set ( "laybyPayments", $laybyPayments );
	}
	/**
	 * 收据
	 */
	public function receipt() {
		// sale编号
		$id = $this->request->params ["id"];
		$id = intval ( $id );
		if (! empty ( $id )) {
			// 查询销售情况
			$data = $this->unsuspend ();
		} else {
			$this->redirect ( "/Sales" );
		}
	}

    public function receipt2() {
        // sale编号
        $id = $this->request->params ["id"];
        $id = intval ( $id );
        if (! empty ( $id )) {
            // 查询销售情况
            $data = $this->unsuspend ();
            // 查询分期付款的支付
            $laybyPayments = array ();
            $options = array (
            		"conditions" => array (
            				"Layby.sale_id" => $id
            		)
            );
            $laybyPayments = $this->LaybyPayment->find ( "all", $options );
            $this->set ( "laybyPayments", $laybyPayments );
        } else {
            $this->redirect ( "/Sales" );
        }
    }


	/**
	 * 删除sale记录
	 */
	public function delete_sale() {
		// sale编号
		$id = $this->request->params ["id"];
		if (! empty ( $id )) {
			// $this->Sale->delete($id);
		}
		$this->redirect ( "/Sales" );
	}
	/**
	 * 查看交易详细
	 */
	public function unsuspend() {
        $ajax=!empty($_REQUEST["ajax"]);
        if ($this->request->is("ajax") || $ajax){
            $this->layout=null;
        }
		$id = $this->request->params ["id"];
		$id = intval ( $id );
		// 销售总表
		$data = $this->Sale->find ( "first", array (
				"conditions" => array (
						"Sale.id" => $id 
				) 
		) );
		if (! empty ( $data )) {
			// 查询item
			$items = $this->findItemsBySaleId ( $id );
			$data ["Customer"] ["name"] = $data ["Customer"] ["first_name"] . " " . $data ["Customer"] ["last_name"];
			$sale = array (
					"id" => $id,
					"cart_count" => ! empty ( $items ) ? count ( $items ) : 0,
					"sub_total" => $data ["Sale"] ["sale_original_price"],
					"created" => $data ["Sale"] ["created"],
					"discount" => $data ["Sale"] ["discount_amout"],
					"discount_type" => $data ["Sale"] ["discount_type"] == "Percentage" ? 0 : 1,
					"payment_type" => 0,
					"payment" => 0,
					"laybyed" => false,
					"total" => $data ["Sale"] ["sale_price"],
					"balance" => $data ["Sale"] ["balance"],
					"customer" => $data ["Customer"],
					"customer_id" => $data ["Sale"] ["customer_id"] 
			);
			$sale_item = array ();
			$sale_item_subtotal = 0;
			$layby_item = array ();
			$layby_item_subtotal = 0;
			$layby_item_amount_subtotal = 0;
			foreach ( $items as $item ) {
				// 正常销售
				if (empty ( $item ["Item"] ["layby_id"] )) {
					$sale_item_subtotal += $item ["Item"] ["total"];
					// 原价减去打折价格
					$sale_item [] = $item;
				} else {
					$layby_item [] = $item;
					$layby_item_subtotal += $item ["Item"] ["total"];
					$layby_item_amount_subtotal += $item ["Item"] ["layby_amount"];
				}
			}
			$sale ["sale_item_subtotal"] = $sale_item_subtotal;
			$sale ["sale_item"] = $sale_item;
			$sale ["layby_item_subtotal"] = $layby_item_subtotal;
			$sale ["layby_item_amount_subtotal"] = $layby_item_amount_subtotal;
			$sale ["layby_item"] = $layby_item;
			$this->set ( "sale", $sale );
			$payment_types = $this->PaymentType->find ( "all" );
			$this->set ( "payment_types", $payment_types );
			// $this->view = "Elements/salesadd";
			// $this->Session->write ( $this->item_session_name, $sale );
			// $this->redirect ( "/Point_of_sale" );
		} else {
			// 没查询到记录
		}
            $this->set("ajax", $ajax);
	}
	// 查看交易详细
	public function complete() {
	}
	/**
	 * ajax查询sale中的项
	 */
	public function sale_items() {
		$this->layout = null;
		// SaleId
		$id = $this->request->params ["id"];
		$items = $this->findItemsBySaleId ( $id );
		$this->set ( "items", $items );
		$this->set ( "sale_id", $id );
	}
	/**
	 * 根据sale编号，查询购物清单
	 */
	private function findItemsBySaleId($id) {
		$sale_items = $this->SaleItem->find ( "all", array (
				"conditions" => array (
						"SaleItem.sale_id" => $id 
				) 
		) );
		$items = array ();
		if (! empty ( $sale_items )) {
			$item_ids = array ();
			$item_sale = array ();
			foreach ( $sale_items as $si ) {
				$item_ids [] = $si ["SaleItem"] ["item_id"];
				$item_sale [$si ["SaleItem"] ["item_id"]] = array (
						"status" => $si ["SaleItem"] ["status"],
						"layby_id" => $si ["SaleItem"] ["layby_id"],
						"layby_amount" => $si ["SaleItem"] ["layby_amount"],
						"discount" => $si ["SaleItem"] ["discount_amount"],
						"discount_type" => $si ["SaleItem"] ["discount_type"] == "Percentage" ? 0 : 1 
				);
			}
			// 查询items
			$items = $this->Item->find ( "all", array (
					"conditions" => array (
							"Item.id" => $item_ids 
					),
					"fields" => array (
							"Item.id",
							"Item.name",
							"Item.original_price",
							"Brand.name",
							"Color.name" 
					) 
			) );
			// 处理items
			foreach ( $items as $k => $v ) {
				$discount = $items [$k] ["Item"] ["discount"] = $item_sale [$v ["Item"] ["id"]] ["discount"];
				$discountType = $items [$k] ["Item"] ["discount_type"] = $item_sale [$v ["Item"] ["id"]] ["discount_type"];
				$layby_id = $items [$k] ["Item"] ["layby_id"] = $item_sale [$v ["Item"] ["id"]] ["layby_id"];
				$layby_amount = $items [$k] ["Item"] ["layby_amount"] = $item_sale [$v ["Item"] ["id"]] ["layby_amount"];
				// 如果有优惠，则计算优惠后的价格
				if (! empty ( $discount )) {
					if (! empty ( $layby_id )) {
						$items [$k] ["Item"] ["total"] = $v ["Item"] ["original_price"] - $layby_amount;
					} else {
						// 优惠金额
						if ($discountType) {
							$items [$k] ["Item"] ["total"] = $v ["Item"] ["original_price"] - doubleval ( $discount );
						} else {
							// 优惠比例
							$items [$k] ["Item"] ["total"] = $items [$k] ["Item"] ["original_price"] * (100 - intval ( $discount )) / 100;
						}
					}
				} else {
					$items [$k] ["Item"] ["total"] = $v ["Item"] ["original_price"];
				}
				$items [$k] ["Item"] ["status"] = $item_sale [$v ["Item"] ["id"]] ["status"];
			}
		}
		return $items;
	}
}